package com.auto.learning.pay;

import java.sql.SQLException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.auto.learning.R;
import com.auto.learning.activity.BookListActivity;
import com.auto.learning.activity.BundingActivity;
import com.auto.learning.activity.MyMoneyActivity;
import com.auto.learning.activity.SubscriptionActivity;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.BookListModel;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.bean.UserVipInfo;
import com.auto.learning.event.BookMoneyEvent;
import com.auto.learning.event.BuySuccessEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.event.listener.OnSubTipClickListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.MyToast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class UserBuyUtils {
	
	public final static int OPERATOR_PLAY = 0;
	public final static int OPERATOR_BUY = 1;
	public final static int OPERATOR_SUB = 2;
	public final static int OPERATOR_READ = 3;
	public final static int OPERATOR_BUY_BOOKLIST = 4;
	
	
	public final static int BOOK_LIST_DOWNLOAD_FREE = 10;
	
	private Context context;
	private int bookId;
	private String priceTag;
	private String bookName;
	private int operatorType = 0; 	// 0:播放提示，1:购买提示, 2:购买VIP，4:购买书单 5 :  6:余额不足充值购买操作
	
	private BookListModel bookListModel;
	private BookMoneyEvent bookmoney;
	/**
	 * 买书
	 * @param context
	 * @param bookId
	 * @param priceTag
	 */
	public UserBuyUtils(Context context , int bookId, String priceTag,String bookName){
		this.context = context;
		this.bookId = bookId;
		this.priceTag = priceTag;
		this.bookName = bookName;
	}
	
	/**
	 * 买书
	 * @param context
	 * @param bookId
	 * @param priceTag
	 * @param operatorType
	 */
	public UserBuyUtils(Context context , int bookId, String priceTag, int operatorType,String bookName){
		this(context, bookId, priceTag,bookName);
		this.operatorType = operatorType;
	}
	

	/**
	 * 购买VIP
	 * @param context
	 * @param operatorType
	 */
	public UserBuyUtils(Context context, int operatorType){
		this.context = context;
		this.operatorType = operatorType;
	}
	public UserBuyUtils(Context context,BookMoneyEvent bookmoney, int operatorType){
		this.context = context;
		this.operatorType = operatorType;
		this.bookmoney=bookmoney;
	}
	
	/**
	 * 书单
	 * @param context
	 * @param bookListModel
	 * @param operatorType
	 */
	public UserBuyUtils(Context context, BookListModel bookListModel, int operatorType){
		this.context = context;
		this.bookListModel = bookListModel;
		this.operatorType = operatorType;
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case BOOK_LIST_DOWNLOAD_FREE:
					if (context != null && context instanceof BookListActivity) {
						((BookListActivity)context).downloadByFree();
					}
					break;
				case HttpRequestHelper.BUY_BOOK_SUCCESS:
					 ResponeResult buyResult = (ResponeResult)msg.obj;
					
					 switch (buyResult.getCode()) {
					 case 0:
						//{"result":{"code":0,"msg":"操作成功"},"data":{"userId":14914,"vipType":3,"vipExpired":"","balanceFen":999601,"balanceYuan":"￥9996.01"}}
						UserVipInfo userVipInfo = new Gson().fromJson(buyResult.getData(), new TypeToken<UserVipInfo>() {}.getType());
						if(operatorType == 6){
							String sql="";
							switch (bookmoney.getType()) {
								case 1:
									//购买书单请求
									if (userVipInfo != null) {
										MyUserInfo.getInstance().getUserInfoBean().setVipInfo(userVipInfo);
										EventBus.getEventBus("m_buy_book_list_success").post(bookmoney.getListid());
										if(context instanceof MyMoneyActivity){
											((MyMoneyActivity)context).finish();
										}else{
											TemporaryVariable.getTopActivity().finish();
										}
									}
								break;
								case 2:
									//购买书籍请求
									 sql = " update book set needBuy = 1  where bookId = "+ bookmoney.getBookId();
									 try {
										 StaticReference.mutilDBSupport.getDao(BookBean.class).queryRaw(sql);
									 } catch (SQLException e) {
										 e.printStackTrace();
									 }
									 EventBus.getEventBus("m_buy_success").post(new BuySuccessEvent(bookmoney.getBookId()));
									 //购买书籍成功减去书籍金钱

									
									UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
									if (userInfoBean.getVipInfo() != null) {
										new MyToast(context, "充值成功", "您已成功购买书籍《"+bookmoney.getBookName()+"》,账户余额"+CommonMethod.calculationMoney(userInfoBean.getVipInfo().getBalanceFen()));
									}
									EventBus.getEventBus("weixin_recharge_success").post(userInfoBean.getVipInfo().getBalanceFen());
									if(context instanceof MyMoneyActivity){
										((MyMoneyActivity)context).finish();
									}else{
										TemporaryVariable.getTopActivity().finish();
									}
								break;
							//充值vip
							case 3:
								 MyUserInfo.getInstance().getUserInfoBean().setVipInfo(userVipInfo);
								  sql = " update book set needBuy = 1 ";
								 try {
										StaticReference.mutilDBSupport.getDao(BookBean.class).queryRaw(sql);
									} catch (SQLException e) {
										e.printStackTrace();
									}
								 EventBus.getEventBus("m_buy_success").post(new BuySuccessEvent(0));
								 new MyToast(context, "订阅成功","您已成功订阅路上读书Vip有效时间："+CommonMethod.formDate(userVipInfo.getVipExpired())+"" );
								 if(context instanceof SubscriptionActivity){
										((SubscriptionActivity)context).setResult(506);
										((SubscriptionActivity)context).finish();
									}else{
										TemporaryVariable.getTopActivity().setResult(560);
										TemporaryVariable.getTopActivity().finish();
									}
								
								break;
							default:
								break;
							
							}
							return;
						}
						if (operatorType == 4 || operatorType == 5) { // 购买书单成功
							if (userVipInfo != null) {
								MyUserInfo.getInstance().getUserInfoBean().setVipInfo(userVipInfo);
								EventBus.getEventBus("m_buy_book_list_success").post(bookListModel.getListId());
							}
						} else {
							if (userVipInfo != null) {
								MyUserInfo.getInstance().getUserInfoBean().setVipInfo(userVipInfo);
								String sql = " update book set needBuy = 1 ";
								if (userVipInfo.getVipType() != 1) {
									sql = " update book set needBuy = 1  where bookId = "+ bookId;
								}
								try {
									StaticReference.mutilDBSupport.getDao(BookBean.class).queryRaw(sql);
								} catch (SQLException e) {
									e.printStackTrace();
								}
								EventBus.getEventBus("m_buy_success").post(new BuySuccessEvent(bookId));
								if (bookId == 0 && context instanceof SubscriptionActivity) {
									((SubscriptionActivity)context).setResult(560);
									((SubscriptionActivity)context).finish();
								}
								if (bookId == 0) {
									CommonMethod.makeNotice(context, "恭喜您成为vip会员！快来畅听吧！");
								}else {
									CommonMethod.makeNotice(context, "谢谢您的打赏！快来畅听吧！");
								}
							}
						}
						break;
					case -203:
						if(operatorType==6 && bookmoney.getType()==1){
							CommonMethod.makeNotice(context, "购买书单失败");
						}
						CommonMethod.showDialog(TemporaryVariable.getTopActivity(), new String[]{"去充值", "取消"}, buyResult.getMsg()+"",new DialogListener() {
							
							@Override
							public void otherButtonClick(Dialog dialog) {
								dialog.dismiss();
							}
							
							@Override
							public void okButtonClick(Dialog dialog) {
								dialog.dismiss();
								Intent intent = new Intent(context, MyMoneyActivity.class);
								try {
									//判断是书单购买还是书籍购买
									int type=0;
									if(bookListModel != null && bookListModel.getListId() > 0){
										type=1;
										intent.putExtra("listId",bookListModel.getListId());
										intent.putExtra("listName", bookListModel.getName());
										intent.putExtra("bookMoney", Double.parseDouble(bookListModel.getNeedMoneyYuan()));
									}else if(bookId > 0){
										type=2;
										intent.putExtra("bookId", bookId);
										intent.putExtra("bookName", bookName);
										intent.putExtra("bookMoney", Double.parseDouble(priceTag));
									}
									intent.putExtra("type", type);
									context.startActivity(intent);
								} catch (Exception e) {
									// TODO: handle exception
								}
							}
							
							@Override
							public void cancelButtonClick(Dialog dialog) {
								dialog.dismiss();
							}
						});
						break;
					case -200:
						CommonMethod.makeNotice(context, buyResult.getMsg()+"");
						break;
					case -201:
						CommonMethod.showDialog(TemporaryVariable.getTopActivity(), new String[]{"现在绑定", "取消"}, buyResult.getMsg()+"",new DialogListener() {
							
							@Override
							public void otherButtonClick(Dialog dialog) {
								dialog.dismiss();
							}
							
							@Override
							public void okButtonClick(Dialog dialog) {
								dialog.dismiss();
								Intent intent = new Intent(context, BundingActivity.class);
								context.startActivity(intent);
							}
							
							@Override
							public void cancelButtonClick(Dialog dialog) {
								dialog.dismiss();
							}
						});
						break;
					}
					break;
				case HttpRequestHelper.BUY_BOOK_FAIL:
					if (msg.obj != null) {
						CommonMethod.makeNotice(context, msg.obj+"");
					}
					break;
			
			
			}
		}
		
	};
	
	public boolean buy(){
		boolean flag = false;
		String alertMsg = "";
		switch (operatorType) {
		case OPERATOR_PLAY:
			alertMsg = context.getString(R.string.text_play_bef_login);
			break;
		case OPERATOR_BUY:
			alertMsg = context.getString(R.string.text_buy_bef_login);
			break;
		case OPERATOR_SUB:
			alertMsg = context.getString(R.string.text_sub_bef_login);
			break;
		case OPERATOR_READ:
			alertMsg = context.getString(R.string.text_read_bef_login);
			break;
		case OPERATOR_BUY_BOOKLIST:
			alertMsg = context.getString(R.string.text_buy_bef_login);
			break;
		}
		if (CommonMethod.checkUserLogin(TemporaryVariable.getTopActivity(), alertMsg)) {
			if (operatorType == 4 || operatorType == 5) {
				flag = buyBookListConfirm();
			} else {
				buyConfirm();
			}
		}
		return flag;
	}
	
	private void buyConfirm(){
		if (!TextUtils.isEmpty(priceTag)) {
			String format = "";
			String alertMsg = "";
			String[] str = new String[]{"购买", "取消"};
			switch (operatorType) {
			case OPERATOR_PLAY:
			case OPERATOR_READ:
				alertMsg = context.getString(R.string.text_confirm_read);
				break;
			case  OPERATOR_BUY:
				alertMsg = context.getString(R.string.text_confirm_buy);
				str = new String[]{"是","否"};
				break;
			default :
				alertMsg = context.getString(R.string.text_confirm_buy);
				break;
			}
			if (!TextUtils.isEmpty(priceTag)) {
				format = String.format(alertMsg, priceTag);
			}
			CommonMethod.showDialog(context, str, format, new DialogListener() {
				@Override
				public void otherButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
				@Override
				public void okButtonClick(Dialog dialog) {
					dialog.dismiss();
					HttpRequestHelper.buy(context, handler, bookId, HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
				}
				@Override
				public void cancelButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
			},context.getString(R.string.text_sub_more_benefit), new OnSubTipClickListener() {
				
				@Override
				public void onSubTipClick(Dialog dialog) {
					Intent intent = new Intent(context, SubscriptionActivity.class);
					context.startActivity(intent);
					dialog.dismiss();
				}
			});
		}else {
			HttpRequestHelper.buy(context, handler, bookId, HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
		}
	}
	//充值后需要去购买书籍还是
	public void tomoney(){
		switch (bookmoney.getType()) {
		case 0:
			//初始值不做任何处理
			break;
		case 1:
			//购买书单请求
			HttpRequestHelper.buyBookList(context, handler, bookmoney.getListid(), HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
			break;
		case 2:
			//购买书籍请求
			HttpRequestHelper.buy(context, handler, bookmoney.getBookId(), HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
			break;
		//充值vip
		case 3:
			HttpRequestHelper.buy(context, handler, 0 , HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
			break;
		default:
			break;
		}
	}
	/**
	 * 购买书单
	 */
	private boolean buyBookListConfirm(){
		boolean flag = true;
		if (bookListModel != null && bookListModel.getListId() > 0) {
			String format = "该书单有%s本付费书籍, 需要￥%s元";
			String[] str = new String[]{"购买", "取消"};
			String alertMsg = "";
			if (bookListModel.getNeedBuyCount() > 0) {
				flag = false;
				if (operatorType == 5) {  //全部收费
					alertMsg = String.format(format, bookListModel.getNeedBuyCount()+"", ""+ (bookListModel.getNeedMoneyYuan()));
					str = new String[]{"购买书单", "放弃购买"};
					CommonMethod.showDialog(context, str, alertMsg, "书单购买",new DialogListener() {
						
						@Override
						public void otherButtonClick(Dialog dialog) {
							dialog.dismiss();
						}
						
						@Override
						public void okButtonClick(Dialog dialog) {
							dialog.dismiss();
							HttpRequestHelper.buyBookList(context, handler, bookListModel.getListId(), HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
						}
						
						@Override
						public void cancelButtonClick(Dialog dialog) {
							dialog.dismiss();
						}
					});
				}else if(operatorType == 4){  //下载按钮
					alertMsg = String.format(format, bookListModel.getNeedBuyCount()+"", ""+ (bookListModel.getNeedMoneyYuan()));
					str = new String[]{"下载免费书籍", "购买付费书籍"};
					CommonMethod.showDialog(context, str, alertMsg, new DialogListener() {
						
						@Override
						public void otherButtonClick(Dialog dialog) {
							dialog.dismiss();
						}
						
						@Override
						public void okButtonClick(Dialog dialog) {
							dialog.dismiss();
							handler.sendEmptyMessage(BOOK_LIST_DOWNLOAD_FREE);
						}
						
						@Override
						public void cancelButtonClick(Dialog dialog) {
							dialog.dismiss();
							//HttpRequestHelper.buyBookList(context, handler, bookListModel.getListId(), HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
							operatorType = 5;
							buyBookListConfirm();
						}
					}, true);
				}
			}
		}
		return flag;
	}
	
	
}
